package com.gzhryc.net_marketing.cloud.business.services;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.net_marketing.cloud.MarketConstants;
import com.gzhryc.net_marketing.cloud.account.dao.db.CloudPayAccount;
import com.gzhryc.net_marketing.cloud.account.dao.enums.CloudPayAccountEnum;
import com.gzhryc.net_marketing.cloud.account.services.CloudPayAccountService;
import com.gzhryc.net_marketing.cloud.business.dao.MarketSupplierDao;
import com.gzhryc.net_marketing.cloud.business.dao.db.MarketSupplier;
import com.gzhryc.net_marketing.cloud.business.dao.enums.MarketSupplierEnum;
import com.gzhryc.net_marketing.cloud.business.services.dto.MarketSupplierSearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;

public class MarketSupplierService {

	static Logger log = Logger.getLogger(MarketSupplierService.class);

    public static MarketSupplierService self() {
        return MultiDBTools.getService(MarketConstants.JDBC_KEY, MarketSupplierService.class, true);
    }

    public static MarketSupplierService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, MarketSupplierService.class, true);
    }

    MarketSupplierDao dao;

    public MarketSupplierService(String jdbcKey) {
        dao = new MarketSupplierDao(jdbcKey);
    }
    
    public List<MarketSupplier> findBySearch(MarketSupplierSearch search,Integer pageNo,Integer pageLimit) {
    	Conditions condition = dao.buildConditions(search);
    	try {
			return dao.findByCondition(condition,pageNo,pageLimit);
		} catch (SQLException e) {
			log.error(e.getMessage(),e);
		}
    	return null;
    }
    
    public Long countBySearch(MarketSupplierSearch search) {
    	Conditions condition = dao.buildConditions(search);
    	try {
			return dao.count(condition);
		} catch (SQLException e) {
			log.error(e.getMessage(),e);
		}
    	return 0L;
    }
    
    public MarketSupplier getById(Long id) {
    	try {
			return dao.getById(id);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
    	return null;
    }
    
    public MarketSupplier getByAccountId(Long accountId) {
    	if(accountId != null) {
    		Conditions condition = new Conditions(MarketSupplier.class);
    		condition.and().is("accountId", accountId);
	    	try {
				return dao.get(condition);
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
    	}
    	return null;
    }
    
    public boolean add(MarketSupplier supplier) throws LogicException{
    	User user = UserService.self().getByPhone(supplier.getUserPhone());
    	if(user == null) {
    		JdbcSession.begin();
            try {
            	user = new User();
            	user.setName(supplier.getUserName());
            	user.setPhone(supplier.getUserPhone());
            	
            	CloudPayAccount cloudPayAccount = new CloudPayAccount();
        	    cloudPayAccount.setSecurityPhone(supplier.getUserPhone());
        	    cloudPayAccount.setType(CloudPayAccountEnum.Type.Supplier.index());
        	    
            	if(UserService.self().add(user)) {
            		supplier.setUserId(user.getId());
            		supplier.setCreateDate(new Date());
            		//添加云支付账号
	                if(CloudPayAccountService.self().add(cloudPayAccount)){
	                	supplier.setAccountId(cloudPayAccount.getId());
	                	if(dao.insert(supplier) > 0){
	                        JdbcSession.commit();
	                        return true;
	                    }
	                }else{
	                    throw new LogicException("新增云支付账号失败");
	                }
            	}else {
            		throw new LogicException("新增用户失败");
            	}
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }finally {
                JdbcSession.end();
            }
    	}else {
    		CloudPayAccount cloudPayAccount = new CloudPayAccount();
    	    cloudPayAccount.setSecurityPhone(user.getPhone());
    	    cloudPayAccount.setType(CloudPayAccountEnum.Type.Supplier.index());
    	    
    	    JdbcSession.begin();
            try {
            	supplier.setUserId(user.getId());
            	supplier.setUserName(user.getName());
            	supplier.setUserPhone(user.getPhone());
            	supplier.setCreateDate(new Date());
            	//添加云支付账号
                if(CloudPayAccountService.self().add(cloudPayAccount)){
                	supplier.setAccountId(cloudPayAccount.getId());
                	if(dao.insert(supplier) > 0){
                        JdbcSession.commit();
                        return true;
                    }
                }else{
                    throw new LogicException("新增云支付账号失败");
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }finally {
                JdbcSession.end();
            }
    	}
    	return false;
    }

    public boolean updateNotNull(MarketSupplier supplier) throws LogicException{
    	try {
			return dao.updateNotNull(supplier) > 0;
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
    	return false;
    }
    
    public boolean updateDbConfig(Long id, String dbConfig) throws LogicException {
        if (id != null && StringUtils.isNotBlank(dbConfig)) {
        	MarketSupplier supplier = new MarketSupplier();
        	supplier.setId(id);
        	supplier.setDbConfig(dbConfig);

            try {
                return dao.updateNotNull(supplier) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }
    
    public boolean toSwitchState(Long id)throws LogicException{
    	MarketSupplier app = this.getById(id);
    	if(app != null) {
    		if(StringTools.isNotBlank(app.getDbConfig())) {
    			MarketSupplier updateEntity = new MarketSupplier();
	    		updateEntity.setId(id);
	    		if(MarketSupplierEnum.State.Enable.index().equals(app.getState())) {
	    			updateEntity.setState(MarketSupplierEnum.State.Wait.index());
	    		}else {
	    			updateEntity.setState(MarketSupplierEnum.State.Enable.index());
	    		}
	    		
	    		try {
					return dao.updateNotNull(updateEntity) > 0;
				} catch (SQLException e) {
					log.error(e.getMessage(), e);
				}
    		}else {
    			throw new LogicException("未配置数据库");
    		}
    	}
    	return false;
    }

    public boolean deleteById(Long id) throws LogicException {
        if (id != null) {
        	MarketSupplier supplier = getById(id);
        	if(supplier != null) {
        		//获取云支付账号
                CloudPayAccount cloudPayAccount = CloudPayAccountService.self().getById(supplier.getAccountId());
                if (cloudPayAccount != null) {
                    if (cloudPayAccount.getMoney() > 0 || cloudPayAccount.getFreezeMoney() > 0) {
                        throw new LogicException("云支付账号存在余额，不允许删除");
                    }
                }
                JdbcSession.begin();
                try {
                    if (dao.deleteById(id) > 0) {
                        //存在则删除云支付账号
                        if (cloudPayAccount != null) {
                            if (CloudPayAccountService.self().faceDeleteById(cloudPayAccount.getId())) {
                                JdbcSession.commit();
                                return true;
                            }
                        } else {
                            JdbcSession.commit();
                            return true;
                        }
                    }
                } catch (SQLException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    JdbcSession.end();
                }
        	}
        }
        return false;
    }
}
